﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Business.Parsers {
    public static class HtmlNodeExtensions {
        private readonly static HtmlNode Null = new HtmlNode(HtmlNodeType.Element, new HtmlDocument(), 0);

        public static HtmlNode NextSibling(this HtmlNode node, string nodeName) {
            var next = node.NextSibling;

            while (next != null) {
                if (string.Compare(next.Name, nodeName, true) == 0)
                    return next;
                next = next.NextSibling;
            }

            return Null;
        }

        public static HtmlNode NearestAncestor(this HtmlNode node, string nodeName) {
            var parent = node.ParentNode;

            while (parent != null) {
                if (string.Compare(parent.Name, nodeName, true) == 0)
                    return parent;
                parent = parent.ParentNode;
            }

            return Null;
        }

        public static HtmlNode FirstChild(this HtmlNode node, string nodeName) {
            var target = node.Children(nodeName).At(0);
            return target ?? Null;
        }

        public static HtmlNode At(this IEnumerable<HtmlNode> nodes, int index) {
            var target = nodes.Skip(index).Take(1).FirstOrDefault();
            return target ?? Null;
        }

        public static IEnumerable<HtmlNode> Children(this HtmlNode node, string nodeName) {
            return node.Descendants(nodeName);
        }

        public static HtmlNode Single(this HtmlNode node, string xpath) {
            var target = node.SelectSingleNode(xpath);
            return target ?? Null;
        }

        public static bool IsNotNull(this HtmlNode node) {
            return node != Null;
        }

        public static IEnumerable<IList<HtmlNode>> Split(this IEnumerable<HtmlNode> source, Func<HtmlNode, bool> separator) {
            var list = new List<HtmlNode>();

            using (var iter = source.GetEnumerator()) {
                while (iter.MoveNext()) {

                    var isSeparator = separator.Invoke(iter.Current);
                    if (isSeparator) {
                        if (list.Count > 0)
                            yield return list;
                        list = new List<HtmlNode>();
                        continue;
                    }

                    list.Add(iter.Current);
                }
            }

            if (list.Count > 0)
                yield return list;
        }

        //public static IEnumerable<HtmlNode> OddNodes(this IEnumerable<HtmlNode> source) {
        //    var odd = false;
        //    foreach (var s in source) {
        //        odd = !odd;
        //        if (odd)
        //            yield return s;
        //    }
        //}
    }
}
